package com.app.system.permission.web.dataBase;


import com.app.system.config.task.MySqlBackRunnable;
import com.app.system.permission.model.DataDict;
import com.app.system.permission.service.DataDictService;
import com.app.system.utils.exception.Response;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 数据库备份定时计划任务启动、停止
 * Created by wcf-pc on 2019/1/26.
 */
@RestController
@RequestMapping("/taskScheduler/*")
@Component
@SuppressWarnings("all")
public class TaskSchedulerController {

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    @Resource
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Resource
    private DataDictService dataDictService;

    /**
     * 定时任务启动（重启）
     *
     * @return
     */
    @RequestMapping("startCron")
    public Response startCron() {
        if (MySqlBackRunnable.future != null) {
            MySqlBackRunnable.future.cancel(true);
        }

        Map<String, DataDict> resultMap = dataDictService.getMapByParentNameForName("系统配置");
        DataDict dataDict = resultMap.get("cronTrigger");
        String cron = "";
        if (dataDict != null) {
            cron = dataDict.getValue();
        }
        if (cron != null && !cron.isEmpty()) {
            MySqlBackRunnable.future = threadPoolTaskScheduler.schedule(new MySqlBackRunnable(), new CronTrigger(cron));
        }

        return new Response("0001", "已启动");
    }

    /**
     * 定时任务关闭
     *
     * @return
     */
    @RequestMapping("stopCron")
    public Response stopCron() {
        if (MySqlBackRunnable.future != null) {
            MySqlBackRunnable.future.cancel(true);
        }
        return new Response("0001", "已停止");
    }

    @RequestMapping("status")
    public Response status() {
        String statusStr = "";
        if (MySqlBackRunnable.future != null) {
            if (MySqlBackRunnable.future.isCancelled()) {
                return new Response("0001", "备份任务已停止");
            } else {
                return new Response("0002", "备份任务启动中");
            }
        }
        return new Response("0000", "未启动");
    }

}
